// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let res = await db.collection('user')
    .where({
      _id: wxContext.OPENID
    })
    .count()
  if (res.total == 0) {
    // 新用户
    await db.collection('user').add({
      data: {
        _id: wxContext.OPENID,
        userInfo: event.userInfo,
        role: 1,
        score: 0
      }
    })
    return (wxContext.OPENID)
  } else {
    // 老用户
    await db.collection('user').doc(wxContext.OPENID).update({
      data: {
        userInfo: event.userInfo
      }
    })
    return (wxContext.OPENID)
  }
}